"""
登录注册界面
"""
import tkinter as tk
from tkinter import ttk, messagebox
import json
import os
import hashlib
import datetime
from typing import Dict, Any, Optional, Callable

class UserManager:
    """用户管理类 - 处理用户注册和登录验证"""

    def __init__(self):
        self.users_file = "users.json"
        self.users_data = {}
        self.load_users()

    def load_users(self):
        """加载用户数据"""
        if os.path.exists(self.users_file):
            try:
                with open(self.users_file, 'r', encoding='utf-8') as f:
                    self.users_data = json.load(f)
                print(f"已加载 {len(self.users_data)} 个用户账户")
            except Exception as e:
                print(f"加载用户数据失败: {e}")
                self.users_data = {}
        else:
            self.users_data = {}

    def save_users(self):
        """保存用户数据"""
        try:
            with open(self.users_file, 'w', encoding='utf-8') as f:
                json.dump(self.users_data, f, ensure_ascii=False, indent=2)
            print("用户数据已保存")
            return True
        except Exception as e:
            print(f"保存用户数据失败: {e}")
            return False

    def hash_password(self, password: str) -> str:
        """对密码进行哈希加密"""
        return hashlib.sha256(password.encode('utf-8')).hexdigest()

    def register_user(self, username: str, password: str) -> tuple:
        """注册用户
        返回: (是否成功, 消息)
        """
        username = username.strip()
        password = password.strip()

        # 验证用户名
        if not username:
            return False, "用户名不能为空"

        if len(username) < 3:
            return False, "用户名长度至少3个字符"

        if len(username) > 20:
            return False, "用户名长度不能超过20个字符"

        # 验证密码
        if not password:
            return False, "密码不能为空"

        if len(password) < 6:
            return False, "密码长度至少6个字符"

        if len(password) > 50:
            return False, "密码长度不能超过50个字符"

        # 检查用户是否已存在
        if username in self.users_data:
            return False, "用户名已存在"

        # 创建用户
        user_data = {
            "username": username,
            "password_hash": self.hash_password(password),
            "register_time": datetime.datetime.now().isoformat(),
            "last_login": None,
            "login_count": 0
        }

        self.users_data[username] = user_data

        if self.save_users():
            return True, "注册成功！"
        else:
            return False, "注册失败：无法保存用户数据"

    def login_user(self, username: str, password: str) -> tuple:
        """用户登录验证
        返回: (是否成功, 消息, 用户数据)
        """
        username = username.strip()
        password = password.strip()

        if not username or not password:
            return False, "用户名和密码不能为空", None

        # 检查用户是否存在
        if username not in self.users_data:
            return False, "用户名不存在", None

        user_data = self.users_data[username]

        # 验证密码
        if user_data["password_hash"] != self.hash_password(password):
            return False, "密码错误", None

        # 更新登录信息
        user_data["last_login"] = datetime.datetime.now().isoformat()
        user_data["login_count"] = user_data.get("login_count", 0) + 1

        self.save_users()

        return True, "登录成功", user_data


class LoginInterface:
    """登录注册界面类"""

    def __init__(self, on_login_success: Optional[Callable] = None):
        self.on_login_success = on_login_success
        self.user_manager = UserManager()
        self.user_config = {}

        # 创建登录窗口
        self.root = tk.Tk()
        self.root.title("游戏智能体 - 用户登录")
        self.root.geometry("450x350")
        self.root.resizable(False, False)

        # 设置主题
        self.root.configure(bg='#1a1a2a')

        # 界面变量
        self.username_var = tk.StringVar()
        self.password_var = tk.StringVar()

        # 当前模式 ('login' 或 'register')
        self.current_mode = 'login'

        # 创建界面
        self.create_interface()

        print("登录注册界面初始化完成")

    def create_interface(self):
        """创建界面"""
        # 主容器
        main_frame = tk.Frame(self.root, bg='#1a1a2a')
        main_frame.pack(fill=tk.BOTH, expand=True, padx=30, pady=30)

        # 标题
        self.title_label = tk.Label(
            main_frame,
            text="游戏智能体",
            font=("Arial", 18, "bold"),
            fg='#4af',
            bg='#1a1a2a'
        )
        self.title_label.pack(pady=20)

        # 模式标题
        self.mode_label = tk.Label(
            main_frame,
            text="用户登录",
            font=("Arial", 14, "bold"),
            fg='white',
            bg='#1a1a2a'
        )
        self.mode_label.pack(pady=10)

        # 输入框架
        input_frame = tk.Frame(main_frame, bg='#2a2a3a', relief=tk.RAISED, bd=2)
        input_frame.pack(fill=tk.X, pady=15)

        # 用户名输入
        self.create_input_field(input_frame, "用户名:", self.username_var, row=0)

        # 密码输入
        self.create_input_field(input_frame, "密  码:", self.password_var, row=1, show="*")

        # 按钮框架
        button_frame = tk.Frame(main_frame, bg='#1a1a2a')
        button_frame.pack(fill=tk.X, pady=20)

        # 登录按钮
        self.login_btn = tk.Button(
            button_frame,
            text="登录",
            command=self.handle_login,
            bg='#4a6a4a',
            fg='white',
            bd=0,
            font=("Arial", 12, "bold"),
            padx=25,
            pady=8,
            width=8
        )
        self.login_btn.pack(side=tk.LEFT, padx=5)

        # 注册按钮
        self.register_btn = tk.Button(
            button_frame,
            text="注册",
            command=self.handle_register,
            bg='#6a4a6a',
            fg='white',
            bd=0,
            font=("Arial", 12, "bold"),
            padx=25,
            pady=8,
            width=8
        )
        self.register_btn.pack(side=tk.LEFT, padx=5)

        # 切换模式按钮 - 增强对比度和可见性
        self.switch_btn = tk.Button(
            button_frame,
            text="切换到注册",
            command=self.switch_mode,
            bg='#5a6a7a',  # 更明亮的蓝灰色
            fg='white',
            bd=1,
            relief=tk.RAISED,
            font=("Arial", 10, "bold"),  # 加粗字体
            padx=15,
            pady=6,
            width=12
        )
        self.switch_btn.pack(side=tk.LEFT, padx=5)

        # 退出按钮
        quit_btn = tk.Button(
            main_frame,
            text="退出",
            command=self.quit_app,
            bg='#6a4a4a',
            fg='white',
            bd=0,
            font=("Arial", 10),
            padx=20,
            pady=6
        )
        quit_btn.pack(pady=10)

        # 状态栏
        self.status_label = tk.Label(
            main_frame,
            text="请输入用户名和密码进行登录",
            fg='#aaa',
            bg='#1a1a2a',
            font=("Arial", 9)
        )
        self.status_label.pack(pady=5)

        # 绑定回车键
        self.root.bind('<Return>', lambda e: self.handle_login() if self.current_mode == 'login' else self.handle_register())

    def create_input_field(self, parent, label_text: str, text_var: tk.StringVar, row: int, show: str = None):
        """创建输入字段"""
        field_frame = tk.Frame(parent, bg='#2a2a3a')
        field_frame.pack(fill=tk.X, padx=15, pady=8)

        # 标签
        label = tk.Label(
            field_frame,
            text=label_text,
            fg='white',
            bg='#2a2a3a',
            font=("Arial", 11),
            width=8
        )
        label.pack(side=tk.LEFT)

        # 输入框
        entry = tk.Entry(
            field_frame,
            textvariable=text_var,
            font=("Arial", 11),
            bg='#3a3a4a',
            fg='white',
            insertbackground='white',
            bd=1,
            relief=tk.SOLID,
            show=show
        )
        entry.pack(side=tk.RIGHT, fill=tk.X, expand=True, padx=10)

        return entry

    def switch_mode(self):
        """切换登录/注册模式"""
        if self.current_mode == 'login':
            self.current_mode = 'register'
            self.mode_label.config(text="用户注册")
            self.switch_btn.config(text="切换到登录", bg='#7a6a5a')  # 注册模式下使用不同颜色
            self.status_label.config(text="请输入用户名和密码进行注册")
        else:
            self.current_mode = 'login'
            self.mode_label.config(text="用户登录")
            self.switch_btn.config(text="切换到注册", bg='#5a6a7a')  # 登录模式下的颜色
            self.status_label.config(text="请输入用户名和密码进行登录")

        # 清空输入框
        self.username_var.set("")
        self.password_var.set("")

    def handle_login(self):
        """处理登录"""
        username = self.username_var.get()
        password = self.password_var.get()

        if not username or not password:
            self.show_status("请输入用户名和密码", "error")
            return

        success, message, user_data = self.user_manager.login_user(username, password)

        if success:
            self.show_status(message, "success")

            # 准备用户配置
            self.user_config = {
                "username": username,
                "user_data": user_data,
                "login_time": datetime.datetime.now().isoformat()
            }

            # 短暂延迟后关闭窗口并启动游戏
            self.root.after(1000, self.login_success)
        else:
            self.show_status(message, "error")

    def handle_register(self):
        """处理注册"""
        username = self.username_var.get()
        password = self.password_var.get()

        if not username or not password:
            self.show_status("请输入用户名和密码", "error")
            return

        success, message = self.user_manager.register_user(username, password)

        if success:
            self.show_status(message, "success")
            # 注册成功后自动切换到登录模式
            self.root.after(1500, lambda: self.switch_mode())
        else:
            self.show_status(message, "error")

    def show_status(self, message: str, msg_type: str = "info"):
        """显示状态消息"""
        colors = {
            "success": "#4a8",
            "error": "#a44",
            "info": "#aaa"
        }

        self.status_label.config(text=message, fg=colors.get(msg_type, "#aaa"))

    def login_success(self):
        """登录成功处理"""
        # 显示成功消息
        messagebox.showinfo(
            "登录成功",
            f"欢迎 {self.user_config['username']}！\n即将进入智能体训练界面..."
        )

        # 关闭登录窗口
        self.root.destroy()

        # 调用成功回调
        if self.on_login_success:
            self.on_login_success(self.user_config)

    def quit_app(self):
        """退出应用"""
        result = messagebox.askyesno("确认退出", "确定要退出游戏智能体吗？")
        if result:
            self.root.destroy()
            exit(0)

    def run(self) -> Dict[str, Any]:
        """运行登录界面并返回用户配置"""
        try:
            # 设置窗口居中
            self.center_window()

            # 聚焦到用户名输入框
            self.root.after(100, lambda: self.root.focus_force())

            self.root.mainloop()
            return getattr(self, 'user_config', {})
        except Exception as e:
            print(f"登录界面运行错误: {e}")
            return {}

    def center_window(self):
        """窗口居中"""
        self.root.update_idletasks()
        width = self.root.winfo_width()
        height = self.root.winfo_height()
        x = (self.root.winfo_screenwidth() // 2) - (width // 2)
        y = (self.root.winfo_screenheight() // 2) - (height // 2)
        self.root.geometry(f'{width}x{height}+{x}+{y}')


# 添加datetime支持
try:
    import datetime
    tk.datetime = datetime
except ImportError:
    pass